<template>
  <view class="w-full min-h-screen bg-gray-50">
    <uni-forms ref="form" :modelValue="formData" :rules="rules" label-position="left">
      <!-- 被访人信息 -->
      <view class="px-4 py-2 bg-gray-100 text-lg font-semibold text-blue-600">被访人信息</view>

      <uni-forms-item label="被访人姓名" required name="hostName" label-width="6rem">
        <uni-easyinput v-model="formData.hostName" placeholder="请输入被访人姓名"/>
      </uni-forms-item>

      <uni-forms-item label="被访人电话" required name="hostPhone" label-width="6rem">
        <uni-easyinput v-model="formData.hostPhone" placeholder="11位手机号" type="number"/>
      </uni-forms-item>

      <uni-forms-item label="访问园区" required name="campus" label-width="6rem">
        <uni-data-select v-model="formData.campus" :localdata="campuses" placeholder="请选择访问园区"/>
      </uni-forms-item>

      <!-- 来访人信息 -->
      <view class="px-4 py-2 bg-gray-100 text-lg font-semibold text-blue-600 mt-4">来访人信息</view>

      <uni-forms-item label="访客类型" required name="visitorType" label-width="6rem">
        <uni-data-select v-model="formData.visitorType" :localdata="visitorTypes" placeholder="请选择访客类型"/>
      </uni-forms-item>

      <uni-forms-item label="人员姓名" required name="visitorName" label-width="6rem">
        <uni-easyinput v-model="formData.visitorName" placeholder="请输入来访人姓名"/>
      </uni-forms-item>

      <uni-forms-item label="电话号码" required name="visitorPhone" label-width="6rem">
        <uni-easyinput v-model="formData.visitorPhone" placeholder="11位手机号" type="number"/>
      </uni-forms-item>

      <!-- 时间选择 -->
      <uni-forms-item label="访问时间" required name="visitTimeRange" label-width="6rem">
        <view class="flex flex-col space-y-2">
          <view class="flex items-center space-x-2">
            <text class="text-gray-500 whitespace-nowrap">开始:</text>
            <uni-datetime-picker
                type="datetime"
                v-model="formData.visitStartTime"
                placeholder="选择开始时间"
                :hide-second="true"
                @change="handleStartTimeChange"
                return-type="date"
                class="flex-1"
            />
          </view>
          <view class="flex items-center space-x-2">
            <text class="text-gray-500 whitespace-nowrap">结束:</text>
            <uni-datetime-picker
                type="datetime"
                v-model="formData.visitEndTime"
                placeholder="选择结束时间"
                :disabled="!formData.visitStartTime"
                :start="formData.visitStartTime"
                :end="sameDayEndTime"
                :hide-second="true"
                @change="handleEndTimeChange"
                return-type="date"
                class="flex-1"
            />
          </view>
        </view>
      </uni-forms-item>

      <uni-forms-item label="来访公司" required name="company" label-width="6rem">
        <uni-easyinput v-model="formData.company" placeholder="请输入来访公司名称"/>
      </uni-forms-item>

      <uni-forms-item label="车牌号" label-width="6rem">
        <uni-easyinput v-model="formData.carNumber" placeholder="选填"/>
      </uni-forms-item>

      <uni-forms-item label="访问事由" required name="purpose" label-width="6rem">
        <uni-easyinput type="textarea" v-model="formData.purpose" placeholder="请说明具体事由"/>
      </uni-forms-item>

      <!-- 陪同人信息 -->
      <view class="px-4 py-2 bg-gray-100 text-lg font-semibold text-blue-600 mt-4">陪同人员信息</view>

      <view v-for="(item, index) in formData.companions" :key="index"
            class="px-4 mb-4 p-3 bg-white rounded-lg shadow-sm">
        <view class="flex justify-between items-center mb-2">
          <text class="font-medium">陪同人 {{ index + 1 }}</text>
          <uni-icons type="close" size="20" color="#f56c6c" @click="removeCompanion(index)"></uni-icons>
        </view>

        <uni-forms-item label="姓名" :required="true" :name="'companionName'+index" label-width="6rem" class="mb-2">
          <uni-easyinput v-model="item.companionName" placeholder="请输入姓名"/>
        </uni-forms-item>

        <uni-forms-item label="电话" :required="true" :name="'companionPhone'+index" label-width="6rem" class="mb-2">
          <uni-easyinput v-model="item.companionPhone" placeholder="11位手机号" type="number"/>
        </uni-forms-item>
      </view>

      <view class="px-4 mb-4">
        <button @click="addCompanion" class="py-2 text-blue-600 border border-blue-600 rounded-lg">
          <uni-icons type="plus" size="16"></uni-icons>
          添加陪同人员
        </button>
      </view>

      <!-- 提交按钮 -->
      <button
          @click="handleSubmit"
          class="mx-4 mt-6 py-3 bg-blue-600 text-white rounded-lg hover:bg-blue-700 active:bg-blue-800 transition-colors"
      >
        提交预约
      </button>
    </uni-forms>
  </view>
</template>

<script setup>
import {computed, onMounted, ref} from 'vue'
import {useRouter} from 'vue-router'
import {getCampuses, getVisitorTypes, reservation} from "@/api/visitor"
import {formatTime} from "@/utils/dateUtils";
import {useAuthStore} from "@/stores/authStore";

const authStore = useAuthStore();

const router = useRouter()
const campuses = ref([])
const visitorTypes = ref([])

// 表单数据（使用时间戳）
const formData = ref({
  visitorType: '',
  hostName: '',
  hostPhone: '',
  campus: '',
  visitorName: '',
  visitorPhone: '',
  company: '',
  visitStartTime: new Date().setSeconds(0, 0),
  visitEndTime: new Date().setHours(23, 59, 0, 0),
  companions: [],
  carNumber: '',
  purpose: '',
  wxOpenid: authStore.wxOpenid,
})
// const formData = ref({
//   visitorType: 'REGULAR',
//   hostName: '龚豪',
//   hostPhone: '18812341234',
//   campus: 'SHENZHEN',
//   visitorName: '张三',
//   visitorPhone: '18812341234',
//   company: '未来科技',
//   visitStartTime: Date.now(), // 使用时间戳
//   visitEndTime: new Date().setHours(23, 59, 0, 0), // 当天23:59的时间戳
//   companions: [
//     {companionName: '陪同1', companionPhone: '18812340000'},
//     {companionName: '陪同2', companionPhone: '18812340001'}
//   ],
//   carNumber: '粤B 1234',
//   purpose: '售前支持',
//   wxOpenid: authStore.wxOpenid,
// })

const form = ref(null)

// 验证规则
const rules = {
  visitorType: {
    rules: [
      {required: true, errorMessage: '请选择访客类型'}
    ]
  },
  hostName: {
    rules: [
      {required: true, errorMessage: '请输入被访人姓名'},
      {minLength: 2, maxLength: 20, errorMessage: '姓名长度2-20个字符'}
    ]
  },
  hostPhone: {
    rules: [
      {required: true, errorMessage: '请输入被访人电话'},
      {pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号码'}
    ]
  },
  campus: {
    rules: [
      {required: true, errorMessage: '请选择访问园区'}
    ]
  },
  company: {
    rules: [
      {required: true, errorMessage: '请输入来访公司名称'},
      {minLength: 2, errorMessage: '公司名称至少2个字符'}
    ]
  },
  visitorName: {
    rules: [
      {required: true, errorMessage: '请输入来访人姓名'},
      {minLength: 2, maxLength: 20, errorMessage: '姓名长度2-20个字符'}
    ]
  },
  visitorPhone: {
    rules: [
      {required: true, errorMessage: '请输入来访人电话'},
      {pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号码'}
    ]
  },
  visitTimeRange: {
    rules: [
      {validateFunction: validateTimeRange}
    ]
  },
  purpose: {
    rules: [
      {required: true, errorMessage: '请输入访问事由'},
      {minLength: 2, errorMessage: '事由至少2个字符'}
    ]
  },
  // 动态生成陪同人验证规则
  ...generateCompanionRules()
}

const fetchCampuses = async () => {
  const res = await getCampuses()
  if (res.code !== 'SUCCESS') {
    return
  }
  campuses.value = res.data.map(item => ({
    text: item.label,
    value: item.value
  }))
}

const fetchVisitorTypes = async () => {
  const res = await getVisitorTypes()
  if (res.code !== 'SUCCESS') {
    return
  }
  visitorTypes.value = res.data.map(item => ({
    text: item.label,
    value: item.value
  }))
}

// 计算属性 - 同一天的结束时间限制
const sameDayEndTime = computed(() => {
  if (!formData.value.visitStartTime) return null
  const startDate = new Date(formData.value.visitStartTime)
  return new Date(startDate.getFullYear(), startDate.getMonth(), startDate.getDate(), 23, 59, 0).getTime()
})

// 时间处理函数
const handleStartTimeChange = (timestamp) => {
  if (!timestamp) {
    formData.value.visitStartTime = null
    formData.value.visitEndTime = null
    return
  }

  formData.value.visitStartTime = timestamp

  // 如果结束时间早于开始时间，清空结束时间
  if (formData.value.visitEndTime && formData.value.visitEndTime <= timestamp) {
    formData.value.visitEndTime = null
  }
}

// 处理结束时间变化
const handleEndTimeChange = (timestamp) => {
  formData.value.visitEndTime = timestamp || null
}

// 生成陪同人验证规则
function generateCompanionRules() {
  const companionRules = {}
  formData.value.companions.forEach((_, index) => {
    companionRules[`companionName`] = {
      rules: [
        {required: true, errorMessage: `请输入陪同人${index + 1}姓名`},
        {minLength: 2, maxLength: 20, errorMessage: '姓名长度2-20个字符'}
      ]
    }
    companionRules[`companionPhone`] = {
      rules: [
        {required: true, errorMessage: `请输入陪同人${index + 1}电话`},
        {pattern: /^1[3-9]\d{9}$/, errorMessage: '请输入正确的手机号码'}
      ]
    }
  })
  return companionRules
}

// 添加陪同人
const addCompanion = () => {
  formData.value.companions.push({companionName: '', companionPhone: ''})
  // 更新验证规则
  Object.assign(rules, generateCompanionRules())
}

// 移除陪同人
const removeCompanion = (index) => {
  formData.value.companions.splice(index, 1)
  // 更新验证规则
  Object.assign(rules, generateCompanionRules())
}

// 自定义时间范围验证
function validateTimeRange(rule, value, callback) {
  if (!formData.value.visitStartTime) {
    callback('请选择开始时间')
  } else if (!formData.value.visitEndTime) {
    callback('请选择结束时间')
  } else {
    const start = new Date(formData.value.visitStartTime)
    const end = new Date(formData.value.visitEndTime)

    // 检查是否同一天
    if (start.getFullYear() !== end.getFullYear() ||
        start.getMonth() !== end.getMonth() ||
        start.getDate() !== end.getDate()) {
      callback('访问时间不能跨天')
      return
    }

    // 检查结束时间是否晚于开始时间
    if (end <= start) {
      callback('结束时间必须晚于开始时间')
      return
    }

    // 检查时间间隔是否合理（至少30分钟）
    const diffMinutes = (end - start) / (1000 * 60)
    if (diffMinutes < 30) {
      callback('访问时间至少需要30分钟')
      return
    }

    callback()
  }
}

// 提交处理
const handleSubmit = async () => {
  try {
    // 手动触发验证
    await form.value.validate()

    // 验证通过后的提交逻辑
    const submitData = {
      ...formData.value,
      visitStartTime: formatTime(formData.value.visitStartTime, 'YYYY-MM-DD HH:mm:00'),
      visitEndTime: formatTime(formData.value.visitEndTime, 'YYYY-MM-DD HH:mm:00')
    }

    const res = await reservation(submitData)
    if (res.code !== 'SUCCESS') {
      return
    }
    await uni.showToast({title: '预约成功', icon: 'none'})
    await uni.switchTab({url: '/pages/history/index'})
  } catch (err) {
    uni.showToast({title: '请检查表单信息', icon: 'none'})
  }
}

// 组件挂载时调用
onMounted(() => {
  fetchCampuses()
  fetchVisitorTypes()
})
</script>

<style scoped>
:deep(.uni-forms-item) {
  padding-left: calc(var(--spacing) * 4);
  padding-right: calc(var(--spacing) * 4);
}
</style>